import React, { useEffect } from "react";
import { Card, Button, Row, Col, Typography, message } from "antd";
import { LockOutlined, UserOutlined, ShoppingOutlined, SettingOutlined } from "@ant-design/icons";
import usePermission from "@/hooks/usePermission";
import { getUserInfoAsync } from "@/store/modules/userSlice";
import { useDispatch, useSelector } from "react-redux";
import store from "@/store";

const { Title, Paragraph } = Typography;


const Home: React.FC = () => {
  const dispatch = useDispatch<typeof store.dispatch>();
  const { hasPermission, hasRole } = usePermission();

  // 模拟数据 - 在实际项目中，这些数据应该从API获取
  const userStats = [
    { title: "今日访问", value: "1,280", icon: <UserOutlined />, color: "#1890ff" },
    { title: "交易总额", value: "¥26,890", icon: <ShoppingOutlined />, color: "#52c41a" },
    { title: "活跃用户", value: "580", icon: <LockOutlined />, color: "#faad14" },
    { title: "系统配置", value: "24", icon: <SettingOutlined />, color: "#f5222d" },
  ];

  // 格式化欢迎信息
  const getWelcomeMessage = () => {
    if (!userInfo) return "欢迎使用管理系统";

    const now = new Date();
    const hour = now.getHours();
    let greeting = "";

    if (hour < 12) {
      greeting = "早上好";
    } else if (hour < 18) {
      greeting = "下午好";
    } else {
      greeting = "晚上好";
    }

    return `${greeting}，${userInfo.username}！`;
  };
  const getUserInfo = async () => {
    try {
      console.log(2222);
      
      await dispatch(getUserInfoAsync()).unwrap();
    } catch (error) {
      message.error("获取用户信息失败");
    }
  };
  const { isLoading, error, userInfo } = useSelector(
    (state: ReturnType<typeof store.getState>) => state.userSlice
  );
  useEffect(() => {
    if (error) {
      message.error(error);
    }
  }, [error]);
  useEffect(() => {
    getUserInfo();
  }, []);

  return (
    <div style={{ padding: "24px" }}>
      {/* 页面标题 */}
      <div style={{ marginBottom: "24px" }}>
        <Title level={3} style={{ marginBottom: "8px" }}>
          {getWelcomeMessage()}
        </Title>
        <Paragraph type="secondary">
          {userInfo
            ? `您当前以${userInfo.userType === "admin" ? "管理员" : "商户"}身份登录`
            : "请登录以访问完整功能"}
        </Paragraph>
      </div>

      {/* 用户信息卡片 */}
      {userInfo && (
        <Card
          title="用户信息"
          style={{ marginBottom: "24px" }}
          extra={
            <Button size="small" onClick={getUserInfo}>
              刷新
            </Button>
          }
        >
          <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
            <img
              src={
                userInfo.avatar ||
                "https://api.dicebear.com/7.x/avataaars/svg?seed=" + userInfo.username
              }
              alt={userInfo.username}
              style={{ width: "64px", height: "64px", borderRadius: "50%", objectFit: "cover" }}
            />
            <div>
              <div style={{ fontSize: "16px", fontWeight: "bold" }}>
                {userInfo.username}
              </div>
              <div style={{ color: "#666", marginTop: "4px" }}>
                账户类型：{userInfo.userType === "admin" ? "管理员" : "商户"}
              </div>
              {userInfo.email && (
                <div style={{ color: "#666", marginTop: "2px" }}>
                  邮箱：{userInfo.email}
                </div>
              )}
              {userInfo.phone && (
                <div style={{ color: "#666", marginTop: "2px" }}>
                  电话：{userInfo.phone}
                </div>
              )}
            </div>
          </div>
        </Card>
      )}

      {/* 数据统计卡片 */}
      <Row gutter={[16, 16]}>
        {userStats.map((stat, index) => (
          <Col xs={24} sm={12} md={6} key={index}>
            <Card
              hoverable
              style={{
                borderRadius: "8px",
                transition: "all 0.3s",
                borderLeft: `4px solid ${stat.color}`,
              }}
            >
              <div
                style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}
              >
                <div>
                  <div style={{ color: "#666", fontSize: "14px", marginBottom: "4px" }}>
                    {stat.title}
                  </div>
                  <div style={{ fontSize: "24px", fontWeight: "bold" }}>{stat.value}</div>
                </div>
                <div style={{ color: stat.color, fontSize: "24px" }}>{stat.icon}</div>
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 系统提示 */}
      <Card title="系统提示" style={{ marginTop: "24px" }}>
        <Paragraph>
          欢迎使用管理系统，这是您的工作控制台。您可以查看最新数据、管理账户信息，或访问系统的各种功能。
        </Paragraph>
        <div style={{ display: "flex", gap: "12px", marginTop: "16px" }}>
          <Button type="primary">前往控制台</Button>
          <Button>查看文档</Button>
          <Button ghost>联系客服</Button>
        </div>
      </Card>

      {/* 权限控制示例 - 根据用户权限显示不同的操作按钮 */}
      <Card title="权限控制示例" style={{ marginTop: "24px" }}>
        <Paragraph type="secondary">以下按钮根据用户角色和权限动态显示</Paragraph>
        <div style={{ display: "flex", flexWrap: "wrap", gap: "12px", marginTop: "16px" }}>
          {/* 所有用户可见的按钮 */}
          <Button>公共操作</Button>

          {/* 仅商户可见的按钮 */}
          {hasRole("merchant") && (
            <Button type="default" style={{ borderColor: "#1890ff", color: "#1890ff" }}>
              商户操作
            </Button>
          )}

          {/* 仅管理员可见的按钮 */}
          {hasRole("admin") && <Button type="primary">管理员操作</Button>}

          {/* 模拟需要特定权限的按钮 */}
          {hasPermission("create_site") && (
            <Button type="dashed">创建站点 (需要create_site权限)</Button>
          )}

          {hasPermission("view_analytics") && (
            <Button type="default" danger>
              查看分析数据 (需要view_analytics权限)
            </Button>
          )}

          {/* 权限演示说明 */}
          <div style={{ marginTop: "16px", width: "100%", color: "#666" }}>
            <p>• 管理员用户可以看到所有按钮</p>
            <p>• 商户用户可以看到公共操作和商户操作按钮</p>
            <p>• 普通用户只能看到公共操作按钮</p>
            <p>• 特定权限按钮需要在用户权限列表中配置相应权限</p>
          </div>
        </div>
      </Card>
    </div>
  );
};

export default Home;
